<template>
  <div class="dynamic-block-content-test">
    <el-card>
      <template #header>
        <h3>动态区块内容测试</h3>
      </template>
      
      <el-row :gutter="24">
        <!-- 区块选择 -->
        <el-col :span="8">
          <h4>选择测试区块</h4>
          <el-select v-model="selectedBlockId" placeholder="请选择区块" @change="loadBlockData">
            <el-option
              v-for="block in blocks"
              :key="block.id"
              :label="`${block.name} (${block.type})`"
              :value="block.id"
            />
          </el-select>
          
          <div v-if="selectedBlock" style="margin-top: 16px;">
            <p><strong>区块名称：</strong>{{ selectedBlock.name }}</p>
            <p><strong>区块类型：</strong>{{ selectedBlock.type }}</p>
            <p><strong>区块ID：</strong>{{ selectedBlock.id }}</p>
          </div>
        </el-col>
        
        <!-- 字段配置 -->
        <el-col :span="16">
          <h4>字段配置</h4>
          <div v-if="fieldsLoading" style="text-align: center; padding: 20px;">
            <el-icon class="is-loading"><Loading /></el-icon>
            <p>加载字段配置中...</p>
          </div>
          
          <div v-else-if="blockFields.length === 0" style="text-align: center; padding: 20px;">
            <el-empty description="该区块暂无字段配置" />
            <el-button type="primary" @click="goToFieldConfig" v-if="selectedBlockId">
              去配置字段
            </el-button>
          </div>
          
          <div v-else>
            <el-table :data="blockFields" border size="small">
              <el-table-column prop="name" label="字段名称" width="120" />
              <el-table-column prop="label" label="字段标签" width="120" />
              <el-table-column prop="type" label="字段类型" width="100" />
              <el-table-column prop="required" label="必填" width="60">
                <template #default="{ row }">
                  <el-tag :type="row.required ? 'danger' : 'info'" size="small">
                    {{ row.required ? '是' : '否' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="orderNum" label="排序" width="60" />
            </el-table>
          </div>
        </el-col>
      </el-row>
      
      <el-divider />
      
      <!-- 内容列表 -->
      <h4>区块内容列表</h4>
      <div v-if="contentLoading" style="text-align: center; padding: 40px;">
        <el-icon class="is-loading"><Loading /></el-icon>
        <p>加载内容中...</p>
      </div>
      
      <div v-else-if="contentList.length === 0" style="text-align: center; padding: 40px;">
        <el-empty description="暂无内容数据" />
      </div>
      
      <div v-else>
        <!-- 动态表格 -->
        <el-table :data="contentList" border>
          <!-- 动态字段列 -->
          <el-table-column
            v-for="field in displayFields"
            :key="field.name"
            :prop="field.name"
            :label="field.label"
            :min-width="getColumnWidth(field)"
            :show-overflow-tooltip="field.type === 'textarea' || field.type === 'editor'"
          >
            <template #default="{ row }">
              <div v-if="field.type === 'image' && getFieldValue(row, field.name)">
                <el-image
                  :src="getFieldValue(row, field.name)"
                  :alt="field.label"
                  style="width: 60px; height: 40px; object-fit: cover;"
                  :preview-src-list="[getFieldValue(row, field.name)]"
                  fit="cover"
                />
              </div>
              <el-tag v-else-if="field.type === 'select'" size="small">
                {{ getFieldValue(row, field.name) }}
              </el-tag>
              <span v-else-if="field.type === 'textarea' || field.type === 'editor'">
                {{ truncateText(getFieldValue(row, field.name), 50) }}
              </span>
              <span v-else>
                {{ getFieldValue(row, field.name) }}
              </span>
            </template>
          </el-table-column>
          
          <!-- 系统字段 -->
          <el-table-column prop="orderNum" label="排序" width="80" />
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <el-divider />
      
      <!-- 调试信息 -->
      <el-collapse>
        <el-collapse-item title="调试信息" name="debug">
          <h5>字段配置数据</h5>
          <pre>{{ JSON.stringify(blockFields, null, 2) }}</pre>
          
          <h5>内容列表数据</h5>
          <pre>{{ JSON.stringify(contentList, null, 2) }}</pre>
          
          <h5>显示字段</h5>
          <pre>{{ JSON.stringify(displayFields, null, 2) }}</pre>
        </el-collapse-item>
      </el-collapse>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { blockApi } from '@/api/block'

const router = useRouter()

// 响应式数据
const selectedBlockId = ref<number | null>(null)
const blocks = ref<any[]>([])
const blockFields = ref<any[]>([])
const contentList = ref<any[]>([])
const fieldsLoading = ref(false)
const contentLoading = ref(false)

// 计算属性
const selectedBlock = computed(() => {
  return blocks.value.find(block => block.id === selectedBlockId.value)
})

const displayFields = computed(() => {
  return blockFields.value.filter(field => {
    const excludeTypes = ['editor']
    return !excludeTypes.includes(field.type) && field.status === 1
  }).sort((a, b) => (a.orderNum || 0) - (b.orderNum || 0))
})

// 方法
const loadBlocks = async () => {
  try {
    const response = await blockApi.getList({ current: 1, size: 100 })
    if (response.code === 0) {
      blocks.value = response.data?.records || response.data?.list || []
    }
  } catch (error) {
    ElMessage.error('加载区块列表失败')
  }
}

const loadBlockFields = async () => {
  if (!selectedBlockId.value) return
  
  fieldsLoading.value = true
  try {
    const response = await blockApi.getFields(selectedBlockId.value)
    if (response.code === 0) {
      blockFields.value = response.data || []
      console.log('加载的字段配置:', blockFields.value)
    }
  } catch (error) {
    console.error('获取字段配置失败:', error)
    ElMessage.error('获取字段配置失败')
  } finally {
    fieldsLoading.value = false
  }
}

const loadBlockContent = async () => {
  if (!selectedBlockId.value) return
  
  contentLoading.value = true
  try {
    const response = await blockApi.getContentList(selectedBlockId.value, {
      page: 1,
      size: 20
    })
    if (response.code === 0) {
      contentList.value = response.data?.list || response.data?.records || []
      console.log('加载的内容列表:', contentList.value)
    }
  } catch (error) {
    console.error('获取内容列表失败:', error)
    ElMessage.error('获取内容列表失败')
  } finally {
    contentLoading.value = false
  }
}

const loadBlockData = async () => {
  if (!selectedBlockId.value) return
  
  await Promise.all([
    loadBlockFields(),
    loadBlockContent()
  ])
}

const getFieldValue = (row: any, fieldName: string) => {
  const fixedFields = ['title', 'subtitle', 'content', 'image', 'link', 'target', 'orderNum', 'status', 'createDate']
  
  if (fixedFields.includes(fieldName)) {
    return row[fieldName] || ''
  } else {
    if (row.attributes) {
      let attributes = row.attributes
      if (typeof attributes === 'string') {
        try {
          attributes = JSON.parse(attributes)
        } catch (e) {
          console.warn('解析attributes失败:', e)
          return ''
        }
      }
      return attributes[fieldName] || ''
    }
    return ''
  }
}

const getColumnWidth = (field: any) => {
  switch (field.type) {
    case 'image':
      return 100
    case 'select':
    case 'radio':
      return 120
    case 'textarea':
      return 200
    case 'editor':
      return 250
    default:
      return 150
  }
}

const truncateText = (text: string, maxLength = 50) => {
  if (!text) return ''
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

const goToFieldConfig = () => {
  router.push(`/content/block/field-config?blockId=${selectedBlockId.value}`)
}

onMounted(() => {
  loadBlocks()
})
</script>

<style scoped lang="scss">
.dynamic-block-content-test {
  padding: 20px;
  
  h4 {
    margin: 0 0 16px 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
  }
  
  h5 {
    margin: 16px 0 8px 0;
    color: #606266;
    font-size: 14px;
    font-weight: 600;
  }
  
  pre {
    background: #f5f5f5;
    padding: 12px;
    border-radius: 4px;
    font-size: 12px;
    max-height: 300px;
    overflow-y: auto;
    margin: 8px 0;
  }
}
</style>
